﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;

public partial class Pub_Module_J_Product : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtPageSize.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btnGo.ClientID + "').click();return false;}} else {return true}; "); 
            string type = this.Attributes["Type"].ToLower();
            if (type == "stall" || type == "saleofpd")
            {
                pnControl.Visible = true;
                ViewState["dtBasket"] = (DataTable)Session["dtBasket"];

                string ActivePage = Request.QueryString["ActivePage"];
                if (Request.QueryString["PageSize"] != "" && Request.QueryString["PageSize"] != null)
                {
                    int iPageSize = int.Parse(Request.QueryString["PageSize"]);
                    if (iPageSize > 100)
                        iPageSize = 100;
                    txtPageSize.Text = iPageSize.ToString();
                }
                else
                {
                    string PageSize = ConfigurationManager.AppSettings["PageSizeViewThumbnail"];
                    txtPageSize.Text = PageSize;
                }

                if (ActivePage == null || ActivePage == "")
                {
                    PagingProduct(0);
                }
                else
                {
                    PagingProduct(int.Parse(ActivePage));
                    lblindex.Text = ActivePage;
                }
            }
            else
            {
                pnControl.Visible = false;
                BindData();
            }
        }

    }
    private void BindData()
    {
        clsWebShop cls = new clsWebShop();
        DataSet ds = null;
        string type = this.Attributes["Type"].ToLower();
        string Cols = this.Attributes["Cols"];
        if (Cols == "" || Cols == null) Cols = "3";
        if (type == "topproduct")
        {
            lblTitleProduct.Text = "SẢN PHẨM MỚI NHẤT";
            string viewcount = System.Configuration.ConfigurationManager.AppSettings["TopPD"];
            ds = cls.Get_Top_ProductNoneProc(viewcount);
        }
        else if (type == "mostproduct")
        {
            lblTitleProduct.Text = "SẢN PHẨM ƯA CHUỘNG NHẤT";
            string viewcount = System.Configuration.ConfigurationManager.AppSettings["MostPD"];
            ds = cls.Get_Most_ProductNoneProc(viewcount);
        }
        else if (type == "topfilm")
        {
            lblTitleProduct.Text = "BỘ PHIM MỚI NHẤT";
            string viewcount = System.Configuration.ConfigurationManager.AppSettings["TopFilm"];
            ds = cls.Get_Top_FilmNoneProc(viewcount);
        }
        else if (type == "samecatproduct")
        {
            lblTitleProduct.Text = "SẢN PHẨM TƯƠNG TỰ";
            string viewcount = System.Configuration.ConfigurationManager.AppSettings["SimilarPD"];
            ds = cls.Get_Similar_ProductNoneProc(viewcount, cls.killSQLInjection(Request.QueryString["PDID"]));

        }
        dtlThumbnail.RepeatColumns = int.Parse(Cols);
        dtlThumbnail.DataSource = ds;
        dtlThumbnail.DataBind();




    }

    private void PagingProduct(int index)
    {
        clsWebShop cls = new clsWebShop();
        clsCommon clsC = new clsCommon();
        string IsSaleOf = "";
        if (this.Attributes["Type"].ToLower() == "saleofpd")
        {
            lblTitleProduct.Text = "sản phẩm khuyến mãi";
            IsSaleOf = "Y";
        }
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("TopicID", clsC.ConvertToDecimal(Request.QueryString["TopicID"]).ToString());
        msg.CreateFirstNode("CatID", clsC.ConvertToDecimal(Request.QueryString["CatID"]).ToString());
        msg.CreateFirstNode("PdName",Request.QueryString["PdName"]);
        msg.CreateFirstNode("CatName", Request.QueryString["CatName"]);
        msg.CreateFirstNode("TopicName", Request.QueryString["TopicName"]);
        msg.CreateFirstNode("IsSaleOf", IsSaleOf);
        msg.CreateFirstNode("StartRecord", index.ToString());
        msg.CreateFirstNode("PageSize", txtPageSize.Text);

        DataSet ds = null;
        ds = cls.Get_ProductByCondition_Paging(msg.GetXmlStr);
        DataTable dtPD = new DataTable();
        DataTable dtCount = new DataTable();

        dtPD = ds.Tables["ProductList"];
        dtCount = ds.Tables["TCounts"];
        if (dtCount.Rows.Count <= 0)
        {
            pnControl.Visible = false;

        }
        else
        {
            if (int.Parse(dtCount.Rows[0]["Counts"].ToString()) > int.Parse(txtPageSize.Text)) //Neu lon hon page size hien Moving Control 
            {
                pnControl.Visible = true;
                lblrecordcount.Text = dtCount.Rows[0]["Counts"].ToString();
                DisplayControlPaging(index);
            }
            else
            {
                pnControl.Visible = false;
                lblrecordcount.Text = dtCount.Rows[0]["Counts"].ToString();
            }
        }


        if (dtPD.Rows.Count > 0)
        {
            if (this.Attributes["Type"].ToLower() != "saleofpd")
            {
                if (Request.QueryString["kind"] != "search")
                {
                    lblTitleProduct.Text = dtPD.Rows[0]["TopicName"].ToString();
                }
                else
                {
                    lblTitleProduct.Text = "<font size='2pt'>Những sản phẩm tìm được</font>";
                }
            }
        }
        else
        {
            lblEmpty.Visible = true;
        }

        dtlThumbnail.RepeatColumns = int.Parse(ConfigurationManager.AppSettings["RepeatColumnThumnail"]);
        dtlThumbnail.DataSource = dtPD;
        dtlThumbnail.DataBind();


    }
    private void DisplayControlPaging(int index)
    {
        lblDisplay.Text = "Số mẩu tin: <b>" + lblrecordcount.Text;
        lblDisplay.Text += "</b> | Trang: <b> ";
        int Display = index / int.Parse(txtPageSize.Text) + 1;
        lblDisplay.Text += Display.ToString();
        lblDisplay.Text += " </b> trên tổng số <b>";
        if (int.Parse(lblrecordcount.Text) % int.Parse(txtPageSize.Text) > 0)
        {
            Display = int.Parse(lblrecordcount.Text) / int.Parse(txtPageSize.Text) + 1;
            lblDisplay.Text += Display.ToString();
        }
        else
        {
            Display = int.Parse(lblrecordcount.Text) / int.Parse(txtPageSize.Text);
            lblDisplay.Text += Display.ToString();
        }

        lblDisplay.Text += " </b> trang";
    }


    protected void dtlThumbnail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        string LinkURL = ResolveUrl("~/") + "Detail/" + CancelAccentedVN(DataBinder.Eval(e.Item.DataItem, "CatName").ToString()) + "/" + DataBinder.Eval(e.Item.DataItem, "PDID").ToString() +"/" + CancelAccentedVN(DataBinder.Eval(e.Item.DataItem, "PDName").ToString());

        string img = ResolveUrl("~/") + DataBinder.Eval(e.Item.DataItem, "ImgUrl").ToString();
        if (DataBinder.Eval(e.Item.DataItem, "ImgUrl").ToString() == "" || DataBinder.Eval(e.Item.DataItem, "ImgUrl") == null)
            img = ResolveUrl("~/") + "Images/Body/Noimages.gif";


        string HTML = "";

        HTML += "<a href='" + img + "'  class='customGal' caption='" + DataBinder.Eval(e.Item.DataItem, "PDName").ToString() + "'>";
        string cssImg = "img_Product";
        if (DataBinder.Eval(e.Item.DataItem, "KindNo").ToString() == "F")
            cssImg = "img_ProductHD";

        HTML += "<img  src='" + img + "'  alt='' title='' border='0'  class='" + cssImg + "' >";
        HTML += "</a>";

        Literal ltlImages = (Literal)e.Item.FindControl("ltlImages");
        ltlImages.Text = HTML;

        Image imgHot = (Image)e.Item.FindControl("imgHot");
        if (DataBinder.Eval(e.Item.DataItem, "IsHot").ToString() == "Y")
        {
            imgHot.Visible = true;
            imgHot.ImageUrl = "~/Images/Icon/hot.gif";
        }
        string sSession = "dtBasket";
        if (DataBinder.Eval(e.Item.DataItem, "KindNo").ToString() == "F")
        {
            sSession="dtBasketFilm";
            Panel pnlKindNo = (Panel)e.Item.FindControl("pnlKindNo");
            pnlKindNo.Visible = false;
            Panel pnlFilm = (Panel)e.Item.FindControl("pnlFilm");
            pnlFilm.Visible = true;
        }

        HtmlImage btnISelect = (HtmlImage)e.Item.FindControl("btnISelect");
        HtmlImage btnICancel = (HtmlImage)e.Item.FindControl("btnICancel");

        Label lblDongia = (Label)e.Item.FindControl("lblDongia");
        lblDongia.Text = FormatMoney(lblDongia.Text);

        Label lblTenSP = (Label)e.Item.FindControl("lblTenSP");
        lblTenSP.Text = "<a href='" + LinkURL + ".aspx' class='lbl_TitleProduct'>" + lblTenSP.Text + "</a>";

        Literal ltrDetail=(Literal)e.Item.FindControl("ltrDetail");
        ltrDetail.Text= "<a href='"+LinkURL+".aspx'><img src='"+ResolveClientUrl("~/")+"Images/Icon/detail.gif'></a>";


        //Discount
        string Price = DataBinder.Eval(e.Item.DataItem, "Price").ToString();
        string Rate = DataBinder.Eval(e.Item.DataItem, "Rate").ToString();
        Panel tdPrice = (Panel)e.Item.FindControl("pnlPrice");


        if (DataBinder.Eval(e.Item.DataItem, "IsSaleOf").ToString() == "Y")
        {
            Panel trSaleOf = (Panel)e.Item.FindControl("pnlSaleOf");
            trSaleOf.Visible = true;

            Label lblDiscountPrice = (Label)e.Item.FindControl("lblDiscountPrice");
            lblDiscountPrice.Text = FormatMoney(lblDiscountPrice.Text);

            tdPrice.Attributes.Add("class", "td_linethrought");

            //get price discount
            Price = DataBinder.Eval(e.Item.DataItem, "DiscountPrice").ToString();
            Rate = DataBinder.Eval(e.Item.DataItem, "DiscountRate").ToString();
        }
        if (DataBinder.Eval(e.Item.DataItem, "Status").ToString() == "C")
        {
            tdPrice.Attributes.Add("class", "td_linethrought");
        }

        if (Session[sSession] != null)
        {
            DataTable dtBasket = (DataTable)Session[sSession];
            if (SearchDataTable(dtBasket, "PDID", DataBinder.Eval(e.Item.DataItem, "PDID").ToString()) != -1) //Neu ton tai san pham nay hien nut cancel
            {
                btnISelect.Style.Add("display", "none");
                btnICancel.Style.Add("display", "block");

            }
        }

       // LinkButton bimgDetail = (LinkButton)e.Item.FindControl("bimgDetail");
      //  bimgDetail.CommandArgument = DataBinder.Eval(e.Item.DataItem, "CatName").ToString() + "☼" + DataBinder.Eval(e.Item.DataItem, "PDID").ToString() + "☼" + DataBinder.Eval(e.Item.DataItem, "PDName").ToString();

    }
    protected void dtlThumbnail_ItemCommand1(object source, DataListCommandEventArgs e)
    {

        if (e.CommandName.ToLower() == "detail")
        {
            string[] strArgument = e.CommandArgument.ToString().Split('☼');
            string TopicName = strArgument[0];
            string PDID = strArgument[1];
            string PDName = strArgument[2];

            Response.Write("<script>window.location.href='" + ResolveUrl("~/") + "Detail/" + CancelAccentedVN(TopicName) + "/" + PDID + "/" + CancelAccentedVN(PDName) + "'</script>");

           /* Response.Redirect(ResolveUrl("~/") +"Detail/"+CancelAccentedVN(TopicName) + "/" + PDID + "/" + CancelAccentedVN(PDName));*/
        }

    }
    
    #region "CommonFunction"
    private int SearchDataTable(DataTable dt, string Col, string value)
    {
        int index = -1;

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i][Col].ToString() == value)
            {
                index = i;
                break;
            }
        }
        return index;
    }
    private string ReturnQueryString(string strQuery)
    {
        string str = "";
        if (Request.QueryString[strQuery] != null && Request.QueryString[strQuery] != "")
        {
            str = strQuery + "=" + Request.QueryString[strQuery];
        }
        return str;
    }

    private string FormatMoney(string sNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", decimal.Parse(sNum));
        }
        catch (Exception) { }
        return sReturn;
    }


    private string FormatMoney(decimal dNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", dNum);
        }
        catch (Exception) { }
        return sReturn;
    }

    private string CancelAccentedVN(string accented)
    {
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\p{IsCombiningDiacriticalMarks}+");
        string strFormD = accented.Normalize(System.Text.NormalizationForm.FormD);
        return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D').Replace(" ", "-").Replace("-", "-").Replace("/", "").Replace(@"\", "").Replace("\"", "").Replace("&", "").Replace("'",""); 
    }

    #endregion

    #region "Event"
    protected void btnINext_Click(object sender, ImageClickEventArgs e)
    {
        int index = int.Parse(lblindex.Text) + int.Parse(txtPageSize.Text);
        if (index < int.Parse(lblrecordcount.Text))
        {
            PagingProduct(index);
            lblindex.Text = index.ToString();
        }
    }
    protected void btnIPre_Click(object sender, ImageClickEventArgs e)
    {
        int index = int.Parse(lblindex.Text) - int.Parse(txtPageSize.Text);
        if (index < 0)
            index = 0;

        PagingProduct(index);
        lblindex.Text = index.ToString();
    }
    protected void btnILast_Click(object sender, ImageClickEventArgs e)
    {

        int iMod = int.Parse(lblrecordcount.Text) % int.Parse(txtPageSize.Text);
        int index;
        if (iMod > 0)
            index = int.Parse(lblrecordcount.Text) - iMod;
        else
            index = int.Parse(lblrecordcount.Text) - int.Parse(txtPageSize.Text);

        PagingProduct(index);
        lblindex.Text = index.ToString();
    }
    protected void btnIFirst_Click(object sender, ImageClickEventArgs e)
    {
        int index = 0;
        PagingProduct(index);
        lblindex.Text = index.ToString();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (int.Parse(txtPageSize.Text) > 100)
            txtPageSize.Text = "100";
        PagingProduct(0);
    }
    #endregion

 
}
